#include "widget.h"
#include "player1.h"
#include "player2.h"
#include "ui_widget.h"
#include <Qpixmap>
#include<QPushButton>
#include<QGraphicsTextItem>
#include <QObject>
#include<QKeyEvent>
#include<qstring.h>

Widget::Widget(QWidget *parent)
    :QWidget(parent)
    ,m_Scene1(this)
    ,Player1S(true)
    ,Player2S(false)
    ,BadmintonIsServed(false)
    ,player1Total(0)
    ,player2Total(0)
    ,Player1Win(false)
    ,Player2Win(false)
    ,page(0)
    ,ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setFixedSize(1270, 819);

    m_Scene0.setSceneRect(QRect(0, 0, 1270, 819));
    stage.setPixmap(QPixmap(":/lng/picture/page11.png"));
    m_Scene0.addItem(&stage);


    m_View.setParent(this);
    m_View.setFixedSize(1271, 823);
    // 关键设置
    m_View.setScene(&m_Scene1);

    m_View.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_View.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 禁用视图变换（可选双重保障）
    m_View.setTransformationAnchor(QGraphicsView::NoAnchor);
    m_View.setResizeAnchor(QGraphicsView::NoAnchor);

    m_View.show();

    m_View.setScene(&m_Scene0);

    skipbtn = new QPushButton;
    skipbtn->setParent(this);
    skipbtn->setFixedSize(200,65);
    skipbtn->setStyleSheet(
        "QPushButton {"
        "   border: none;"                        // 去掉边框
        "   background-image: url(:/lng/picture/skipbtn.png);" // 正常状态图片
        "   background-repeat: no-repeat;"        // 禁止重复平铺
        "   background-position: center;"         // 图片居中
        "}"
        );
    skipbtn->move(200,710);
    skipbtn->show();
    connect(skipbtn,&QPushButton::clicked,this,&Widget::initmainmenu);//点击按钮后切换场景

    nextbtn = new QPushButton;
    nextbtn->setParent(this);
    nextbtn->setFixedSize(200,65);
    nextbtn->setStyleSheet(
        "QPushButton {"
        "   border: none;"                        // 去掉边框
        "   background-image: url(:/lng/picture/next.png);" // 正常状态图片
        "   background-repeat: no-repeat;"        // 禁止重复平铺
        "   background-position: center;"         // 图片居中
        "}"
        );
    nextbtn->move(850,710);
    nextbtn->show();
    connect(nextbtn,&QPushButton::clicked,this,&Widget::UpdateStage);//点击按钮后切换场景

    sound = new QSoundEffect();
    sound->setSource(QUrl::fromLocalFile(":/lng/picture/page0sound.WAV"));
    sound->setVolume(0.3);
    sound->setLoopCount(1);
    sound->play();
}
void Widget::UpdateStage()
{
    QString pagepath;
    QString soundpath;


    if(page == 6)
    {
        initmainmenu();
    }

    soundpath = QString(":/lng/picture/page%1sound.WAV").arg(page+1);
    sound->setSource(QUrl::fromLocalFile(soundpath));
    sound->setVolume(0.3);
    sound->setLoopCount(1);
    sound->play();

    pagepath = QString(":/lng/picture/page%1.jpg").arg(page);
    page++;
    stage.setPixmap(QPixmap(pagepath));
}


void Widget::InitGame()
{
    sound->stop();

    backsound = new QSoundEffect();
    backsound->setSource(QUrl::fromLocalFile(":/lng/picture/backsound.WAV"));
    backsound->setVolume(0.1);
    backsound->setLoopCount(QSoundEffect::Infinite);
    backsound->play();


    //切换游戏场景
    QPixmap bgPixmap1(":/lng/picture/GameBackGround.png");
    bgPixmap1 = bgPixmap1.scaled(1270, 819); // 确保图片严格匹配场景尺寸
    m_Scene2.setSceneRect(QRect(0, 0, 1270, 819));
    m_BackGround2.setPixmap(bgPixmap1);
    m_Scene2.addItem(&m_BackGround2);
    m_View.setScene(&m_Scene2);

    //删除初始按钮
    delete Startbtn;
    Startbtn = nullptr;

    //设置Player1
    player1 = new Player1();
    player1->setPos(250,600);
    m_Scene2.addItem(player1);
    m_Scene2.addItem(player1->m_Racket);

    // 假设球拍把手固定在火柴人图片底部中心位置 少了这步一开始球拍不在火柴人身上
    QPointF FixedPos = player1->pos() + QPointF(player1->boundingRect().width() / 2 - 3, player1->boundingRect().height()/2 - 20);
    player1->m_Racket->SetStickPosition(FixedPos);


    //设置Player2
    player2 = new Player2();
    player2->setPos(1000,600);
    m_Scene2.addItem(player2);
    m_Scene2.addItem(player2->m_Racket);

    // 假设球拍把手固定在火柴人图片底部中心位置 少了这步一开始球拍不在火柴人身上（重要）
    QPointF FixedPos1 = player2->pos() + QPointF(player2->boundingRect().width() / 2 - 3, player2->boundingRect().height()/2 - 20);
    player2->m_Racket->SetStickPosition(FixedPos1);

    m_View.setFocus();//添加焦点 使其可以检测按键

    //绘制空气墙
    // 创建空气墙，这里以场景底部为例
    QGraphicsRectItem *AirWall1 = new QGraphicsRectItem(0 , 0 , 50 , 1000); //左空气墙
    QGraphicsRectItem *AirWall2 = new QGraphicsRectItem(607 , 610 , 40 , 200); //球网空气墙
    QGraphicsRectItem *AirWall3 = new QGraphicsRectItem(1170 , 0 , 50 , 1000); //右空气墙
    AirWall1->setPen(Qt::NoPen); // 不绘制边框
    m_Scene2.addItem(AirWall1);
    AirWall2->setPen(Qt::NoPen); // 不绘制边框
    m_Scene2.addItem(AirWall2);
    AirWall3->setPen(Qt::NoPen); // 不绘制边框
    m_Scene2.addItem(AirWall3);

    //建立羽毛球
    //传入badminton
    badminton = new Badminton();
    badminton->setPlayers(player1,player2);
    badminton->setAirWall(AirWall1,AirWall2,AirWall3);

    //添加比分表
    ScoreMap = new QGraphicsPixmapItem();
    ScoreMap->setPixmap(QPixmap(":/lng/picture/00.png"));
    m_Scene2.addItem(ScoreMap);
    ScoreMap->setPos(520,30);

    // 在InitGame()函数中连接信号
    // 羽毛球创建后添加落地信号连接
    connect(badminton, &Badminton::landed, this, &Widget::badmintonLanded);

    //游戏结束槽信号
    connect(this, &Widget::GameFinish, this, &Widget::FinishGame);
}


void Widget::initmainmenu()
{
    sound->stop();

    //释放指针
    delete skipbtn;
    skipbtn = nullptr;
    delete nextbtn;
    nextbtn = nullptr;

    Startbtn = new QPushButton;
    m_Scene1.setSceneRect(QRect(0, 0, 1270, 819));
    QPixmap bgPixmap1(":/lng/picture/205gate.png");
    bgPixmap1 = bgPixmap1.scaled(1270, 819); // 确保图片严格匹配场景尺寸
    m_BackGround1.setPixmap(bgPixmap1);
    m_Scene1.addItem(&m_BackGround1);

    p1Picture.setPixmap(QPixmap(":/lng/picture/Player1introduce.png"));
    p2Picture.setPixmap(QPixmap(":/lng/picture/Player2Introduce.png"));
    m_Scene1.addItem(&p2Picture);
    p2Picture.setPos(760,50);
    m_Scene1.addItem(&p1Picture);
    p1Picture.setPos(0,60);

    m_View.setScene(&m_Scene1);
    //开始按钮
    Startbtn->setParent(this);
    Startbtn->setFixedSize(800,65);
    Startbtn->setStyleSheet(
        "QPushButton {"
        "   border: none;"                        // 去掉边框
        "   background-image: url(:/lng/picture/Startbtn.png);" // 正常状态图片
        "   background-repeat: no-repeat;"        // 禁止重复平铺
        "   background-position: center;"         // 图片居中
        "}"
        "QPushButton:hover {"
        "   background-image: url(:/lng/picture/StartbtnHover.png);"  // 鼠标悬停状态图片
        "}"
        );
    Startbtn->move(240,610);
    Startbtn->show();

    connect(Startbtn,&QPushButton::clicked,this,&Widget::InitGame);//点击按钮后切换场景
}



//检测羽毛球落地
//比分增长
void Widget::IncreaseScore(int player1Score, int player2Score) {

    if(BadmintonIsServed)
    {
        player1Total += player1Score;
        player2Total += player2Score;
    }
    

    //判断游戏是否结束
    //玩家一获胜
    if(player1Total == 5)
    {
        Player1Win = true;
        emit GameFinish();
    }

    //玩家二获胜
    if(player2Total == 5)
    {
        Player2Win = true;
        emit GameFinish();
    }


    // 更新显示文本
    if(player1Total == 0 && player2Total == 1)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/01.png"));
    }
    if(player1Total == 0 && player2Total == 2)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/02.png"));
    }
    if(player1Total == 0 && player2Total == 3)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/03.png"));
    }
    if(player1Total == 0 && player2Total == 4)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/04.png"));
    }
    if(player1Total == 1 && player2Total == 0)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/10.png"));
    }
    if(player1Total == 1 && player2Total == 1)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/11.png"));
    }
    if(player1Total == 1 && player2Total == 2)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/12.png"));
    }
    if(player1Total == 1 && player2Total == 3)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/13.png"));
    }
    if(player1Total == 1 && player2Total == 4)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/14.png"));
    }
    if(player1Total == 2 && player2Total == 0)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/20.png"));
    }
    if(player1Total == 2 && player2Total == 1)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/21.png"));
    }
    if(player1Total == 2 && player2Total == 2)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/22.png"));
    }
    if(player1Total == 2 && player2Total == 3)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/23.png"));
    }
    if(player1Total == 2 && player2Total == 4)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/24.png"));
    }
    if(player1Total == 3 && player2Total == 0)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/30.png"));
    }
    if(player1Total == 3 && player2Total == 1)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/31.png"));
    }
    if(player1Total == 3 && player2Total == 2)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/32.png"));
    }
    if(player1Total == 3 && player2Total == 3)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/33.png"));
    }
    if(player1Total == 3 && player2Total == 4)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/34.png"));
    }
    if(player1Total == 4 && player2Total == 0)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/40.png"));
    }
    if(player1Total == 4 && player2Total == 1)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/41.png"));
    }
    if(player1Total == 4 && player2Total == 2)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/42.png"));
    }
    if(player1Total == 4 && player2Total == 3)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/43.png"));
    }
    if(player1Total == 4 && player2Total == 4)
    {
        ScoreMap->setPixmap(QPixmap(":/lng/picture/44.png"));
    }
}


// 在badmintonLanded()函数中添加计分逻辑
void Widget::badmintonLanded()
{

    //判断加分
    if(m_Scene2.items().contains(badminton))
    {
        if((*badminton).x() > 647)
        {
            // 球落在右侧，玩家1得分
            IncreaseScore(1, 0);  // 玩家1加1分
            Player1S = true;
            Player2S = false;
        }
        if((*badminton).x() < 647)
        {
            // 球落在左侧，玩家2得分
            IncreaseScore(0, 1);  // 玩家2加1分
            Player2S = true;
            Player1S = false;
        }
        m_Scene2.removeItem(badminton);
    }

    //重置发球
    player1->Played = !Player1S;
    player2->Played = !Player2S;

    //重置羽毛球速度及状态
    (*badminton).Vx = 0;
    (*badminton).Vy = 0;
    BadmintonIsServed = false;
}


void Widget::FinishGame()
{
    backsound->stop();

    victorysound = new QSoundEffect();
    victorysound->setSource(QUrl::fromLocalFile(":/lng/picture/victory.WAV"));
    victorysound->setVolume(0.1);
    victorysound->setLoopCount(1);
    victorysound->play();



    victorysound = new QSoundEffect();
    //设置背景
    m_Scene3.setSceneRect(QRect(0, 0, 1270, 819));
    m_BackGround3.setPixmap(QPixmap(":/lng/picture/BackGround3.png"));
    m_Scene3.addItem(&m_BackGround3);


    //判断哪方胜利
    if(Player1Win)
    {
        p1Picture.setPixmap(QPixmap(":/lng/picture/Player1Kill.jpg"));
        m_Scene3.addItem(&p1Picture);
        FinishItem.setPos(460,50);
        p1Picture.setPos(0,0);
        player1Finish.setPixmap(QPixmap(":/lng/picture/Player1Victory.png"));
        m_Scene3.addItem(&player1Finish);
        player1Finish.setPos(80,150);
        player2Finish.setPixmap(QPixmap(":/lng/picture/Player2Lose.png"));
        m_Scene3.addItem(&player2Finish);
        player2Finish.setPos(870,250);
    }

    if(Player2Win)
    {
        //背景
        FinishItem.setPixmap(QPixmap(":/lng/picture/Player2Choose.jpg"));
        m_Scene3.addItem(&FinishItem);

        //处死按钮
        Killbtn = new QPushButton;
        Killbtn->setParent(this);
        Killbtn->setFixedSize(200,70); //切换场景后记得删除btn
        Killbtn->setStyleSheet(
            "QPushButton {"
            "   border: none;"                        // 去掉边框
            "   background-image: url(:/lng/picture/Killbtn.png);" // 正常状态图片
            "   background-repeat: no-repeat;"        // 禁止重复平铺
            "   background-position: center;"         // 图片居中
            "}"
            );
        Killbtn->move(400,650);
        Killbtn->show();

        connect(Killbtn,&QPushButton::clicked,this,&Widget::InitKillend);//点击按钮后切换场景

        //饶恕按钮
        Forgivebtn = new QPushButton;
        Forgivebtn->setParent(this);
        Forgivebtn->setFixedSize(200,70); //切换场景后记得删除btn
        Forgivebtn->setStyleSheet(
            "QPushButton {"
            "   border: none;"                        // 去掉边框
            "   background-image: url(:/lng/picture/Forgivebtn.png);" // 正常状态图片
            "   background-repeat: no-repeat;"        // 禁止重复平铺
            "   background-position: center;"         // 图片居中
            "}"
            );
        Forgivebtn->move(700,650);
        Forgivebtn->show();

        connect(Forgivebtn,&QPushButton::clicked,this,&Widget::InitForgiveend);//点击按钮后切换场景
    }

    //视图显示
    m_View.setScene(&m_Scene3);
}


//处死结局
void Widget::InitKillend()
{
    //删除按钮 且重新设为空指针
    delete Forgivebtn;
    Forgivebtn = nullptr;
    delete Killbtn;
    Killbtn = nullptr;

    //设置场景
    m_Scene4.setSceneRect(QRect(0, 0, 1270, 819));
    KillBackGround.setPixmap(QPixmap(":/lng/picture/Killend.jpg"));
    m_Scene4.addItem(&KillBackGround);

    player1Finish.setPixmap(QPixmap(":/lng/picture/Player1Lose.png"));
    m_Scene4.addItem(&player1Finish);
    player1Finish.setPos(40,180);
    player2Finish.setPixmap(QPixmap(":/lng/picture/Player2Win.png"));
    m_Scene4.addItem(&player2Finish);
    player2Finish.setPos(900,240);

    m_View.setScene(&m_Scene4);
}


//饶恕结局
void Widget::InitForgiveend()
{
    //删除按钮 且重新设为空指针
    delete Forgivebtn;
    Forgivebtn = nullptr;
    delete Killbtn;
    Killbtn = nullptr;

    //设置场景
    m_Scene5.setSceneRect(QRect(0, 0, 1270, 819));
    ForgiveBackGround.setPixmap(QPixmap(":/lng/picture/Forgiveend.jpg"));
    m_Scene5.addItem(&ForgiveBackGround);

    player1Finish.setPixmap(QPixmap(":/lng/picture/Player1Lose.png"));
    m_Scene5.addItem(&player1Finish);
    player1Finish.setPos(40,180);
    player2Finish.setPixmap(QPixmap(":/lng/picture/Player2Win.png"));
    m_Scene5.addItem(&player2Finish);
    player2Finish.setPos(900,240);

    m_View.setScene(&m_Scene5);
}


//按键检测
void Widget::keyPressEvent(QKeyEvent *event)
{
    if (!m_pressedKeys.contains(event->key()))
    {
        m_pressedKeys.append(event->key());
    }

    if (m_pressedKeys.contains(Qt::Key_A))
    {
        (*player1).m_MoveLeftFlag = true;
        (*player1).m_MoveTimer->start(8);
    }

    if (m_pressedKeys.contains(Qt::Key_D))
    {
        (*player1).m_MoveRightFlag = true;
        (*player1).m_MoveTimer->start(8);
    }

    if (m_pressedKeys.contains(Qt::Key_W))
    {
        if(!(*player1).m_MoveUpFlag)
        {
            (*player1).m_MoveUpFlag = true;
            (*player1).m_OriginalY = (*player1).y();
            (*player1).m_JumpTimer->start(8);
        }
    }

    if (m_pressedKeys.contains(Qt::Key_S))
    {
        //如果球未被发出 且轮到player1发球 则添加badminton 进行发球
        if(Player1S&&!BadmintonIsServed)
        {
            m_Scene2.addItem(badminton);
            badminton->setPos((*player1).x(),(*player1).y()-40);
            player1->Played =false;
            player2->Played =true;
            (*badminton).Vx = 12;
            (*badminton).Vy = -14;
            BadmintonIsServed = !BadmintonIsServed;
        }

        //旋转球拍
        //如果不是正在进行挥拍动作 则可以触发按键响应
        if(!(*player1).m_MoveRollFlag&&!(*player1).m_MoveRollDownFlag)
        {
            //上手击球
            if((*badminton).y() < 565)
            {
                (*player1).m_MoveRollFlag = true;
                (*player1).m_RollTimer->start(8);
                (*player1).m_Racket->RotateRacket((*player1).m_RacketAngle);
            }

            //如果球低于一定高度 换为下手击球
            else
            {
                (*player1).m_MoveRollDownFlag = true;
                (*player1).m_RollTimer->start(8);
                (*player1).m_Racket->RotateRacket((*player1).m_RacketAngle);
            }
        }
    }

    if (m_pressedKeys.contains(Qt::Key_J))
    {
        (*player2).m_MoveLeftFlag = true;
        (*player2).m_MoveTimer->start(8);
    }

    if (m_pressedKeys.contains(Qt::Key_L))
    {
       (*player2).m_MoveRightFlag = true;
        (*player2).m_MoveTimer->start(8);
    }

    if (m_pressedKeys.contains(Qt::Key_I))
    {
        //如果不是正在进行跳跃动作 则可响应跳跃
        if(!(*player2).m_MoveUpFlag)
        {
            (*player2).m_MoveUpFlag = true;
            (*player2).m_OriginalY = (*player2).y();
            (*player2).m_JumpTimer->start(8);
        }
    }

    if (m_pressedKeys.contains(Qt::Key_K))
    {
        //如果球未被发出 且轮到player1发球 则添加badminton 进行发球
        if(Player2S&&!BadmintonIsServed)
        {
            m_Scene2.addItem(badminton);
            badminton->setPos((*player2).x(),(*player2).y()-30);
            player2->Played =false;
            player1->Played =true;
            (*badminton).Vx = -12;
            (*badminton).Vy = -14;
            BadmintonIsServed = !BadmintonIsServed;
        }

        // 旋转球拍
        //如果不是正在进行挥拍动作 则可以触发按键响应
        if(!(*player2).m_MoveRollFlag&&!(*player2).m_MoveRollDownFlag)
        {
            //上手挥拍
            if((*badminton).y() < 565)
            {
                (*player2).m_MoveRollFlag = true;
                (*player2).m_RollTimer->start(8);
                (*player2).m_Racket->RotateRacket((*player2).m_RacketAngle);
            }

            //如果球低于一定高度 换为下手击球
            else
            {
                (*player2).m_MoveRollDownFlag = true;
                (*player2).m_RollTimer->start(8);
                (*player2).m_Racket->RotateRacket((*player2).m_RacketAngle);
            }
        }
    }
    QWidget::keyPressEvent(event);
}


void Widget::keyReleaseEvent(QKeyEvent *event)
{
    if(m_pressedKeys.contains(event->key()))
    {
        m_pressedKeys.removeOne(event->key());
    }

    // 玩家1移动释放
    if (!m_pressedKeys.contains(Qt::Key_A))
    {
        (*player1).m_MoveLeftFlag = false;
    }

    if (!m_pressedKeys.contains(Qt::Key_D))
    {
        (*player1).m_MoveRightFlag = false;
    }

    // 玩家2移动释放
    if (!m_pressedKeys.contains(Qt::Key_J)) {
        (*player2).m_MoveLeftFlag = false;
    }

    if (!m_pressedKeys.contains(Qt::Key_L)) {
        (*player2).m_MoveRightFlag = false;
    }

    // 停止移动计时器
    if (!(*player1).m_MoveLeftFlag && !(*player1).m_MoveRightFlag) {
        (*player1).m_MoveTimer->stop();
    }
    if (!(*player2).m_MoveLeftFlag && !(*player2).m_MoveRightFlag) {
        (*player2).m_MoveTimer->stop();
    }

    // 跳跃键释放处理
    if (event->key() == Qt::Key_W || event->key() == Qt::Key_I)
    {
        // 跳跃释放不做特殊处理，在move函数中终止计时器
    }

    // 挥拍键释放处理
    if (event->key() == Qt::Key_S || event->key() == Qt::Key_K)
    {
        // 挥拍释放不做特殊处理，在挥拍动画完成后自动停止
    }

    //如果不再左走右走则停止计时器
    if (!(*player2).m_MoveLeftFlag && !(*player2).m_MoveRightFlag)
    {
        (*player2).m_MoveTimer->stop();
    }

    if (!(*player1).m_MoveLeftFlag && !(*player1).m_MoveRightFlag)
    {
        (*player1).m_MoveTimer->stop();
    }
    QWidget::keyReleaseEvent(event);

}

Widget::~Widget()
{
    delete ui;
}
